#!/usr/bin/env python3
"""
检查MySQL时区支持
"""

import pymysql

# 数据库配置
DB_CONFIG = {
    'host': '192.168.37.11',
    'port': 3306,
    'user': 'root',
    'password': '123456',
    'database': 'data_plexus',
    'charset': 'utf8mb4'
}

def check_mysql_timezone():
    try:
        connection = pymysql.connect(**DB_CONFIG)
        cursor = connection.cursor()
        
        print('检查MySQL时区支持...')
        print('=' * 50)
        
        # 检查MySQL版本
        cursor.execute('SELECT VERSION()')
        version = cursor.fetchone()[0]
        print(f'MySQL版本: {version}')
        
        # 检查时区表是否有数据
        cursor.execute('SELECT COUNT(*) FROM mysql.time_zone_name')
        tz_count = cursor.fetchone()[0]
        print(f'时区表记录数: {tz_count}')
        
        if tz_count > 0:
            # 查找亚洲时区
            cursor.execute("SELECT name FROM mysql.time_zone_name WHERE name LIKE '%Asia%' ORDER BY name LIMIT 10")
            asia_zones = cursor.fetchall()
            print('\n可用的亚洲时区:')
            for zone in asia_zones:
                print(f'  {zone[0]}')
            
            # 查找上海时区
            cursor.execute("SELECT name FROM mysql.time_zone_name WHERE name LIKE '%Shanghai%'")
            shanghai_zones = cursor.fetchall()
            print('\n上海相关时区:')
            for zone in shanghai_zones:
                print(f'  {zone[0]}')
            
            # 测试 Asia/Shanghai
            try:
                cursor.execute("SET time_zone = 'Asia/Shanghai'")
                cursor.execute('SELECT @@session.time_zone, NOW()')
                result = cursor.fetchone()
                session_tz, current_time = result
                print(f'\n✅ Asia/Shanghai 测试成功')
                print(f'会话时区: {session_tz}')
                print(f'当前时间: {current_time}')
                return True
            except Exception as e:
                print(f'\n❌ Asia/Shanghai 测试失败: {e}')
                return False
        else:
            print('\n❌ 时区表为空，需要加载时区数据')
            print('对于MySQL 8.0，请执行以下步骤:')
            print('1. 在MySQL服务器上运行:')
            print('   mysql_tzinfo_to_sql /usr/share/zoneinfo | mysql -u root -p mysql')
            print('2. 或者在Windows上，下载时区数据并导入')
            return False
        
        connection.close()
        
    except Exception as e:
        print(f'检查失败: {e}')
        return False

if __name__ == "__main__":
    success = check_mysql_timezone()
    if not success:
        print("\n建议: 如果无法加载时区数据，可以继续使用 +08:00 格式")
